package com.zxp.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxp.mall.common.exception.NoStockException;
import com.zxp.mall.common.to.OrderTo;
import com.zxp.mall.common.to.mq.StockDetailTo;
import com.zxp.mall.common.to.mq.StockLockedTo;
import com.zxp.mall.common.utils.PageUtils;
import com.zxp.mall.common.utils.Query;
import com.zxp.mall.common.utils.R;
import com.zxp.mall.ware.dao.WareSkuDao;
import com.zxp.mall.ware.entity.WareOrderTaskDetailEntity;
import com.zxp.mall.ware.entity.WareOrderTaskEntity;
import com.zxp.mall.ware.entity.WareSkuEntity;
import com.zxp.mall.ware.feign.OrderFeignService;
import com.zxp.mall.ware.feign.ProductFeignService;
import com.zxp.mall.ware.service.WareOrderTaskDetailService;
import com.zxp.mall.ware.service.WareOrderTaskService;
import com.zxp.mall.ware.service.WareSkuService;
import com.zxp.mall.ware.vo.OrderItemVo;
import com.zxp.mall.ware.vo.OrderVo;
import com.zxp.mall.ware.vo.SkuHasStockVo;
import com.zxp.mall.ware.vo.WareSkuLockVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
@Slf4j
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    OrderFeignService orderFeignService;


    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        this.baseMapper.unLockStock(skuId, wareId, num);
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskDetailId);
        wareOrderTaskDetailEntity.setLockStatus(2); // 变更为已经解锁
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
//        判断有没有这个库存记录 有就是更新 没有就是新增
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(
                new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id", skuId)
                        .eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntities)) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            try {
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) r.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
//                失败事务不需要回滚
                log.error("调用product失败");
            }
            this.save(wareSkuEntity);
        } else {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo stockVo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(skuId);
            stockVo.setSkuId(skuId);
            stockVo.setHasStock(count == null ? false : count > 0);
            return stockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

//        保存库存工作单的详情 追溯
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            skuWareHasStock.setSkuId(skuId);
//            查询商品在哪个仓库有库存
            List<Long> wareIds = baseMapper.listWareIdHasStock(skuId);
            skuWareHasStock.setWareId(wareIds);
            skuWareHasStock.setNum(item.getCount());
            return skuWareHasStock;
        }).collect(Collectors.toList());

        for (SkuWareHasStock skuStock : collect) {
            Long skuId = skuStock.getSkuId();
            Boolean skuStocked = false;
            List<Long> wareIds = skuStock.getWareId();

            if (CollectionUtils.isEmpty(wareIds)) {
//                没有任何仓库有此商品的库存
                throw new NoStockException(skuId);
            }
//            如果锁定成功 将当前商品锁定了几件的工作单记录发送到mq
//            如果锁定失败 前面保存的工作单信息回滚了 发送出去的消息要解锁记录 由于去数据库查不到指定id 所以也不用解锁
            for (Long wareId : wareIds) {
                Long count = baseMapper.lockSkuStock(skuId, wareId, skuStock.getNum());
                if (count == 1) {
//                    锁定成功
                    skuStocked = true;
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(
                            null,
                            skuId,
                            "",
                            skuStock.getNum(),
                            taskEntity.getId(),
                            wareId,
                            1
                    );
                    wareOrderTaskDetailService.save(detailEntity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity, stockDetailTo);
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                } else {
//                    锁定失败
                }
            }
            System.out.println("skuStocked ====>" + skuStocked);
            if (skuStocked == false) {
//                所有商品都没有锁住
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        System.out.println("收到解锁库存的消息");
        StockDetailTo detail = to.getDetail();
        /**
         * 查询数据库关于这个订单的锁定库存消息
         * 有，证明库存锁定成功
         *      解锁：根据订单情况
         *          1.没有订单 必须解锁
         *          2.有这个订单
         *              订单状态：已取消的解锁库存 没取消的不能解锁库存
         * 没有 证明锁定库存失败了 无需解锁
         */
        Long detailId = detail.getId();
//        查询数据库关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (byId != null) {
//            把库存加回去
            Long id = to.getId(); // 库存工作单的id
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
//            拿到订单号
            String orderSn = taskEntity.getOrderSn();
//            查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });

//                已取消的解锁库存
                if (orderVo == null || orderVo.getStatus() == 4) {
                    if (byId.getLockStatus() == 1) {
//                        当前库存工作单详情 状态为1 已解锁但是
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                throw new RuntimeException("远程服务失败");
            }

        } else {
//            无需解锁
        }
    }

    //    防止订单服务卡顿导致订单状态一直改不了 库存消息优先到期 查订单状态新建 什么都不做就走了 导致卡顿的订单永远不能解锁库存
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
//        查询最新的库存工作单
        WareOrderTaskEntity entity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = entity.getId();
        List<WareOrderTaskDetailEntity> detailEntities = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detailEntity : detailEntities) {
            unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum(), detailEntity.getId());
        }
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}